#!/usr/bin/python

from cgi import parse, parse_qs
import sys
import time
import traceback


def application(env, start_response):

    if env["REQUEST_METHOD"] != "POST":
        start_response(("400 Bad Request"),[("Content-Type","text/html")])
        return ["<b>wrong paramter</b>"]
    q=env["QUERY_STRING"]

    
    if not env.has_key("CONTENT_LENGTH"):
        start_response(("400 Bad Request"),[("Content-Type","text/html")])
        return ["<b>wrong paramter</b>"]

    q1=parse_qs(q)
    if not q1.has_key("name"):
        start_response(("400 Bad Request"),[("Content-Type","text/html")])
        return ["<b>wrong paramter</b>"]

    b_size = 4096
    acc=q1["name"][0]
    data_in = env["wsgi.input"]
    c_len = int(env["CONTENT_LENGTH"])
    c_time = time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())
    fn="/var/www/html/log/%s_%s.txt" % (acc,c_time)
    
    c_times = c_len / b_size
    #c_last = c_len % b_size
    try:
        fp = open(fn,"wb")
    except:
        traceback.print_exc()
        start_response(("500 Server Error"),[("Content-Type","text/html")])
        return ["<b>server error</b>"]
    try:
        remain = c_len
        while True:
            if remain <= 0:
                break
            if remain < b_size:
                d = data_in.read(remain)
            else:
                d = data_in.read(b_size)
            if not d:
                break
            remain -= len(d)
            fp.write(d)
    except:
        traceback.print_exc()
        start_response(("500 Server Error"),[("Content-Type","text/html")])
        return ["<b>server error</b>"]
    finally:
        fp.close()

    #print d
    start_response(("200 OK"),[("Content-Type","text/plain")])
    res=[]
    #for k,v in env.items():
    #    res.append("%s = %s\n" % (str(k),str(v)))
    return res


if __name__ == "__main__":
    from gevent.pywsgi import WSGIServer
    WSGIServer(('',80), application).serve_forever()
